package com.lidong.framework.web.editor;

import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.lidong.framework.util.DateUtil;
import com.lidong.framework.util.StringUtil;

/**
 * 对于需要转换为Date类型的属性，使用DateEditor进行处理
 */
public class DatePropertyEditor extends PropertyEditorSupport {

	/**
	 * Parse the Date from the given text, using the specified DateFormat.
	 */
	@Override
	public void setAsText(String text){
		if (StringUtil.isBlank(text)) {
			setValue(null);
			return;
		}
		Pattern pattern = Pattern.compile(":");
		Matcher matcher = pattern.matcher(text);
		int matchCnt = 0;
		while (matcher.find()) {
			matchCnt ++;
		}
		switch (matchCnt) {
			case 2:
				setValue(DateUtil.format(text, DateUtil.FORMAT_YMDHMS));
				break;
			case 1:
				setValue(DateUtil.format(text, DateUtil.FORMAT_YMDHM));
				break;
			default:
				if(text.contains(" ")){
					setValue(DateUtil.format(text, DateUtil.FORMAT_YMDH));
				}else{
					setValue(DateUtil.format(text, DateUtil.FORMAT_YMD));
				}
				break;
		}
	}

	/**
	 * Format the Date as String, using the specified DateFormat.
	 */
	@Override
	public String getAsText() {
		Date value = (Date) getValue();
		return (value != null ? DateUtil.formatYMDHMS(value) : "");
	}
}